import os
import time

from flask import current_app
from werkzeug.utils import secure_filename

from cn.wubo.util.Util import make_dir, file_suffix
from config import UPLOAD_FOLDER


class File(object):
    def __init__(self, file, key1, key2, key3):
        self.file = file
        self.key1 = key1
        self.key2 = key2
        self.key3 = key3

    def file_check(self, models):
        current_app.logger.info('检查是否已上传')
        current_app.logger.info('传入参数key1:%s key2:%s key3:%s', self.key1, self.key2, self.key3)
        filters = {'key1': self.key1, 'key2': self.key2, 'key3': self.key3}
        has = models.FileKey.query.filter_by(**filters).all()
        if len(has) > 0:
            return False, '关键字重复'
        else:
            return True, ''

    def file_save(self, models, db):
        uploadname = secure_filename(self.file.filename)
        filename = str(time.time()).replace('.', '') + '.' + file_suffix(self.file.filename)
        make_dir(UPLOAD_FOLDER)
        path = os.path.join(UPLOAD_FOLDER, filename)
        self.file.save(path)
        current_app.logger.info('上传文件%s存储到服务器 位置为%s', uploadname, path)
        self.file.seek(0, 0)
        # upload_file = models.UploadFile(self.file.read(), path)
        upload_file = models.UploadFile(None, path)
        db.session.add(upload_file)
        db.session.commit()
        current_app.logger.info('上传文件%s存储到数据库 id为%s', uploadname, upload_file.id)
        file_key = models.FileKey(upload_file.id, uploadname, self.key1, self.key2, self.key3)
        db.session.add(file_key)
        db.session.commit()
        current_app.logger.info('上传文件%s存储索引信息存到数据库 id为%s', uploadname, file_key.id)
        return True, '文件%s上传成功' % uploadname
